package com.demo.action;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.demo.model.MenuInfo;
import com.demo.service.MenuService;
import com.opensymphony.xwork2.ActionSupport;

public class MenuAction extends ActionSupport {

	protected final Log log = LogFactory.getLog(getClass());

	private MenuService menuService;
	private MenuInfo menuInfo;
	private String json = "";
	private String menuId = "0";

	public MenuService getMenuService() {
		return menuService;
	}

	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public MenuInfo getMenuInfo() {
		return menuInfo;
	}

	public void setMenuInfo(MenuInfo menuInfo) {
		this.menuInfo = menuInfo;
	}

	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}

	public String getMenuId() {
		return menuId;
	}

	public void setMenuId(String menuId) {
		this.menuId = menuId;
	}

	public String getSubMenu() {
		if (this.log.isDebugEnabled()) {
			this.log.debug("getmenu by menu id:" + menuId);
		}

		int superId = 0;
		if ((this.menuId != null) && (!"".equals(this.menuId))
				&& menuId.matches("^-?\\d+$")) {
			superId = Integer.parseInt(menuId);
		}

		List<MenuInfo> menus = menuService.getSubMenu(superId);
		StringBuffer menu = new StringBuffer();

		for (MenuInfo item : menus) {
			if ((menu != null) && (!"".equals(menu.toString()))) {
				menu.append(",");
			}
			menu.append("{");
			menu.append("\"text\":\"").append(item.getName()).append("\"");
			menu.append(",\"id\":\"").append(item.getId()).append("\"");

			if ((item.getUrl() != null) && (!"".equals(item.getUrl()))) {
				menu.append(",\"url\":\"").append(item.getUrl()).append("\"");
			}

			if ((item.getTitle() != null) && (!"".equals(item.getTitle()))) {
				menu.append(",\"title\":\"").append(item.getTitle())
						.append("\"");
			}

			if (!item.getLeaf()) {
				menu.append(",\"cls\":\"folder\"");
			} else {
				if ((item.getImgCls() != null)
						&& (!"".equals(item.getImgCls())))
					menu.append(",\"cls\":\"").append(item.getImgCls())
							.append("\"");
				else {
					menu.append(",\"cls\":\"file\"");
				}
				menu.append(",\"leaf\":true");
			}
			menu.append("}");
		}

		this.json = ("[" + menu.toString() + "]");
		return "json";
	}
}
